﻿Imports System.IO
Imports System.IO.Stream
Imports System.Text
Imports System.Text.RegularExpressions

Public Class FileParse
    'In:
    Private _file2parse As String
    Private _folder2parse As String
    Private _exts As String

    'Out:
    Private _extention As String
    Private _dimentions As String
    Private _bitdepth As Integer
    Private _tags As String
    Private _rating As Integer
    Private _datesaved As Date
    Private _datecreated As Date
    Private _dateaccessed As Date
    Private _date As Date

    'Derived:
    Private _dimentionsX As Integer
    Private _dimentionsY As Integer



    Property FileToParse() As String
        Get
            Return _file2parse
        End Get
        Set(value As String)
            _file2parse = value
        End Set
    End Property

    Property FolderToParse() As String
        Get
            Return _folder2parse
        End Get
        Set(value As String)
            _folder2parse = value
        End Set
    End Property

    Property Extentions() As String
        Get
            Return _exts
        End Get
        Set(value As String)
            _exts = value
        End Set
    End Property

    Private _fullDets As Boolean = False
    Public Property FullDetails() As Boolean
        Get
            Return _fullDets
        End Get
        Set(ByVal value As Boolean)
            _fullDets = value
        End Set
    End Property



    Public Function FolderParse(FolderName As String)

        'Database Games entries matched on "Name" in Files table

        Debug.WriteLine(vbCr & "========== FILE PARSE =============")
        Debug.WriteLine("FOLDER: " & _folder2parse.ToString)
        Debug.WriteLine("Extentions: " & _exts)

        'Sub wide vars
        Dim FileDT As DataTable = GameSetMatch._GSMDS.Tables("Files")


        'Determine Folder row.
        Dim FolderRow() As DataRow
        Dim FolderID As Integer
        FolderRow = GameSetMatch._GSMDS.Tables("Folders").Select("FolderName='" & FolderName & "'")
        FolderID = FolderRow(0).Item("ID")


        ' FILTER files + produce file list:
        'Create Array of files matching filter:
        Dim alFiles As ArrayList = New ArrayList()
        ' Create an array of filter string
        Dim MultipleFilters() As String = _exts.Split(";")
        ' for each filter find mathing file names
        For Each FileFilter As String In MultipleFilters
            ' add found file names to array list

            alFiles.AddRange(Directory.GetFiles(_folder2parse, FileFilter, SearchOption.TopDirectoryOnly))
        Next

        GameSetMatch.OperationLB.Text = "Parsing Files in Folder: [" & FolderName & "]"
        GameSetMatch.PB1.Minimum = 0
        GameSetMatch.PB1.Maximum = alFiles.Count + 1
        Dim count As Integer = 0
        Application.DoEvents()

        'PERFORM operaitons on each file
        Dim newrow As DataRow
        Dim MatchText As String = Nothing
        FileDT.BeginLoadData()

        For Each File As String In alFiles
            ' Debug.WriteLine("-----------------------------------------------------------------------------------------------------------------------------------")
            ' Debug.WriteLine("File: " & File)
            newrow = FileDT.NewRow
            newrow("FolderID") = FolderID

            If My.Settings.MatchRemBrackets = True Then
                MatchText = RemoveBracketedText(Path.GetFileNameWithoutExtension(File)).Trim
            Else
                MatchText = Path.GetFileNameWithoutExtension(File).Trim
            End If
            newrow("Name") = MatchText


            Dim fi As New IO.FileInfo(File)
            'Filename:
            newrow("FileName") = fi.Name
            ' Get file extension
            newrow("FileExtention") = fi.Extension
            ' Get directory name
            ' File Exists ?
            Dim exists As Boolean = fi.Exists
            'Debug.WriteLine("File Exists: {0}", exists)
            If fi.Exists Then 'And _fullDets Then
                ' Get file size
                newrow("FileSize") = Format(fi.Length / 1024, "##,##0.00")
                ' File ReadOnly ?
                newrow("ReadOnly?") = fi.IsReadOnly
                ' Creation, last access, and last write time
                newrow("DateAccessed") = fi.LastAccessTime
                newrow("DateLastSaved") = fi.LastWriteTime
                newrow("DateCreated") = fi.CreationTime
                Try
                    Using fs As New FileStream(File, FileMode.Open)
                        Using img As Image = Image.FromStream(fs, False, False)
                            '  Debug.WriteLine(Path.GetFileName(File).PadRight(25) + img.Width.ToString() + " " + img.Height.ToString() + " " + fs.Position.ToString() + " ")
                            newrow("Height") = img.Height
                            newrow("Width") = img.Width
                            newrow("Tag") = img.Tag
                            newrow("VPpi") = Format(img.VerticalResolution, "#.0")
                            newrow("HPpi") = Format(img.VerticalResolution, "#.0")
                            newrow("BitDepth") = img.PixelFormat
                        End Using
                    End Using
                Catch ex As Exception
                    Debug.WriteLine("ERROR: During image.Stream...")
                End Try
            End If
            'Image Properties

            FileDT.Rows.Add(newrow)

            count = count + 1
            GameSetMatch.PB1.Value = count
            Application.DoEvents()
        Next
        FileDT.EndLoadData()



        Return True
    End Function

    Private Function FileStream(file2parse As String) As FileStream
        Throw New NotImplementedException
    End Function

    Public Function RemoveBracketedText(Str As String) As String

        Str = Regex.Replace(Str, "\[(.*?)\]", "")
        Str = Regex.Replace(Str, "\((.*?)\)", "")
        Return Str

    End Function

End Class
